package com.educal.Controller;

import com.educal.Bean.Teacher;
import com.educal.Repository.StuRepository;
import com.educal.Repository.TeacherRepository;
import com.educal.Until.FileUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by miyang on 2018/1/11.
 */
@RestController
public class TeacherController {
    @Autowired
    private TeacherRepository teacherRepository;

    @PutMapping(value = "/teachers/password")
    public Map<String,Object> updatePwd(@RequestParam("tId") String tId,
                                        @RequestParam("tPassword") String tPassword ) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        Teacher teacher = new Teacher();
        List<Teacher> list = teacherRepository.findAll();
        for (int i = 0; i < list.size(); i++) {
            String teaId = list.get(i).getTid();
            if (teaId.equals(tId)) {
                teacher.setTid(teaId);
                teacher.setTname(list.get(i).getTname());
                teacher.setTpassword(tPassword);
                teacher.setTcollege(list.get(i).getTcollege());
                teacher.setPosition(list.get(i).getPosition());
                teacher.setPhone(list.get(i).getPhone());
                teacherRepository.save(teacher);
                result.put("code", 200);
                result.put("stu", teacher);
                break;
            }
        }
        return result;
    }

    //处理文件上传
    @PostMapping(value = "/upload")
    public Map<String,Object> uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String,Object> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("code",400);
        }
        String contentType =file.getContentType();
        String fileName = file.getOriginalFilename();
        String filePath = "D://test//";
        //  String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
//        System.out.println(filePath);
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            result.put("code",200);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }
}
